﻿using InfonavaEye.common;
using InfonavaEye.components;
using InfonavaEye.model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace InfonavaEye.Forms
{
    public partial class SelectBoxTemplateStep1Form : Form
    {
        /// <summary>
        /// 正在修改的钉盒模板
        /// </summary>
        private string editBoxModelName;
        private List<Nail> oldTemplateNailList;
        public string selectBoxModelName;
        public BoxModel boxModel;
        private BoxTemplatePreview boxTemplatePreview = new BoxTemplatePreview();
        private List<string> boxNames = new List<string>();

        /// <summary>
        /// 模板的钉子 (主要是记录了钉子的选中状态，方便自动化的时候处理)
        /// </summary>
        public List<Nail> templateNailList = null;

        public SelectBoxTemplateStep1Form(string templateName, List<Nail> oldTemplateNailList)
        {
            InitializeComponent();
            boxTemplatePreview.scaleRate = 1 / 24f;
            this.editBoxModelName = templateName;
        }

        private void SelectBoxTemplateStep1Form_Load(object sender, EventArgs e)
        {
            this.loadTemplateList();
        }

        private void loadTemplateList()
        {
            var baseDir = util.FileHelper.getBaseDir();
            DirectoryInfo TheFolder = new DirectoryInfo(baseDir + "\\BoxModel");
            List<FileInfo> filelist = TheFolder.GetFiles().OrderByDescending(fi => fi.LastWriteTime).ToList();
            List<DataGridViewRow> rows = new List<DataGridViewRow>();
            int i = 0;
            foreach (FileInfo file in filelist)
            {
                //只显示正常的模板（非正常的为删除的模板）
                if (file.Name.EndsWith(".json"))
                {
                    string itemText = file.Name.Replace(".json", "");
                    //this.cmbTemplate.Items.Add(itemText);
                    DataGridViewRow row = new DataGridViewRow();
                    row.MinimumHeight = 45;
                    row.Cells.AddRange(new DataGridViewCell[]{
                        new DataGridViewTextBoxCell() {
                            Value=i,
                        },
                        new DataGridViewTextBoxCell() {
                            Value=itemText,
                        },
                    });
                    rows.Add(row);
                    boxNames.Add(itemText);
                    i++;
                }
            }
            dataGridView.Rows.AddRange(rows.ToArray());
            cmbTemplateList.Items.AddRange(boxNames.ToArray());
            //选中上一个
            this.selectDefaultRow();
        }

        private void selectDefaultRow() {
            Task.Run(async () =>
            {
                await Task.Delay(200);
                if (boxNames.Count > 0)
                {
                    if (this.editBoxModelName != null)
                    {
                        int findIndex = boxNames.FindIndex(p => p.Equals(this.editBoxModelName));
                        if (findIndex > -1)
                        {
                            this.dataGridView.CurrentCell = this.dataGridView.Rows[findIndex].Cells[0];
                            CurrentRowChanged(findIndex);
                            return;
                        }
                    }
                    this.dataGridView.CurrentCell = this.dataGridView.Rows[0].Cells[0];
                    CurrentRowChanged(0);
                }
            });
        }

        int currentRowIndex = 0;

        private void CurrentRowChanged(int rowIndex)
        {
            this.BeginInvoke(new Action(() =>
            {
                try
                {
                    Console.WriteLine("CurrentRowChanged:"+rowIndex);
                    currentRowIndex = rowIndex;
                    string boxModelName = dataGridView.Rows[rowIndex].Cells[1].Value.ToString();
                    this.selectBoxModelName = boxModelName;
                    this.boxModel = BoxModelHelper.parseBoxModel(boxModelName);
                    // NailShape 1.脊柱钉类, 2.创伤圆钉类  3.板棒类 
                    this.lblNailShape.Text = this.boxModel.NailShape == 1 ? "脊柱钉类" : "创伤圆钉类";
                    this.lblTemplateName.Text = boxModelName;
                    boxTemplatePreview.drawAreas(previewPicBox, this.boxModel);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("选择钉盒模板列表切换行发生异常，异常：{0},详细信息：{1}", ex.Message, ex.StackTrace);
                }
            }));
        }

        private void previewPicBox_Paint(object sender, PaintEventArgs e)
        {

        }

        private void dataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            //点击的是标题栏
            if (e.RowIndex == -1)
            {
                return;
            }

            int rowIndex = e.RowIndex;
            CurrentRowChanged(rowIndex);
        }

        /// <summary>
        /// 校准原点的位置（x,y）
        /// </summary>
        public XYZ[] fixZeroLocation;

        private void btnSure_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.selectBoxModelName)) {
                MessageBox.Show("请选择一个模板");
                return;
            }

            SelectBoxTemplateForm form = new SelectBoxTemplateForm(this.selectBoxModelName,
              this.selectBoxModelName.Equals(this.editBoxModelName)?this.oldTemplateNailList : null);
            form.boxModel = this.boxModel;
            var dialogResult = form.ShowDialog();
            if (dialogResult == DialogResult.OK)
            {
                this.fixZeroLocation = form.fixZeroLocation;
                this.templateNailList = form.boxTemplatePreview.nailList;
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
        }

        private void btnBack_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            var templateName = cmbTemplateList.SelectedItem.ToString();
            int findIndex = boxNames.FindIndex(p => p.Equals(templateName));
            if (findIndex > -1)
            {
                this.dataGridView.CurrentCell = this.dataGridView.Rows[findIndex].Cells[0];
                CurrentRowChanged(findIndex);
            }
        }

        private void cmbTemplateList_TextUpdate(object sender, EventArgs e)
        {
            ComboBox cbBox = (ComboBox)sender;
            List<string> listNew = new List<string>();
            cbBox.Items.Clear();
            foreach (var item in boxNames)  //已有数据
            {
                if (item.Contains(cbBox.Text))
                {
                    listNew.Add(item);
                }
            }
            cbBox.Items.AddRange(listNew.ToArray());
            cbBox.SelectionStart = cbBox.Text.Length;
            Cursor = Cursors.Default;
            cbBox.DroppedDown = true;
        }

        private void dataGridView_Paint(object sender, PaintEventArgs e)
        {
            //定义边框矩形位置
            Rectangle rect = new Rectangle(0, 0, this.dataGridView.Width - 1, this.dataGridView.Height - 1);
            //定义画笔颜色
            Pen p = new Pen(Color.FromArgb(193, 193, 193));
            //或者选择颜色枚举Pen p = Pens.DarkGray;
            //画
            e.Graphics.DrawRectangle(p, rect);
        }
    }
}
